<template>
  <div class="app-container">
    <div class="preview-header">
      <el-form :inline="true">
        <el-form-item label="文件路径">
          <el-input
            v-model="fileUrl"
            placeholder="请输入文件路径"
            clearable
            style="width: 400px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handlePreview">预览</el-button>
        </el-form-item>
        <el-form-item>
          <el-upload
            class="upload-demo"
            :action="uploadFileUrl"
            :headers="headers"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="handleBeforeUpload"
            :show-file-list="false"
          >
            <el-button type="success">上传文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
    </div>

    <div class="preview-content" v-loading="loading">
      <template v-if="showPreview">
        <!-- PDF预览 -->
        <div v-if="fileType === 'pdf'" class="pdf-preview">
          <pdf-viewer :url="fileUrl" />
        </div>
        <!-- Excel预览 -->
        <div v-else-if="['xls', 'xlsx'].includes(fileType)" class="excel-preview">
          <el-table :data="excelData" border style="width: 100%" height="560">
            <el-table-column
              v-for="(col, index) in excelColumns"
              :key="index"
              :prop="col"
              :label="col"
              show-overflow-tooltip
            />
          </el-table>
        </div>
        <!-- 图片预览 -->
        <el-image
          v-else-if="fileType === 'image'"
          :src="fileUrl"
          fit="contain"
          style="width: 100%; max-height: 600px"
          :preview-src-list="[fileUrl]"
        >
          <template #error>
            <div class="image-slot">
              <el-icon><picture-filled /></el-icon>
            </div>
          </template>
        </el-image>
        <!-- Office文档预览 -->
        <div v-else-if="['doc', 'docx'].includes(fileType)" class="doc-preview" v-html="docContent"></div>
        <!-- 文本文件预览 -->
        <div v-else-if="fileType === 'txt'" class="text-preview">
          <pre>{{ fileContent }}</pre>
        </div>
        <!-- 不支持的文件类型 -->
        <div v-else class="empty-content">
          <el-empty description="暂不支持该类型文件的预览" />
        </div>
      </template>
      <div v-else class="empty-content">
        <el-empty description="请输入文件路径或上传文件进行预览" />
      </div>
    </div>
  </div>
</template>

<script setup name="FilePreview">
import { ref, computed, getCurrentInstance } from 'vue';
import { ElMessage } from 'element-plus';
import { getToken } from '@/utils/auth';
import { PictureFilled } from '@element-plus/icons-vue';
import mammoth from 'mammoth';
import * as XLSX from 'xlsx';
import PdfViewer from '@/components/PdfViewer/index.vue';

const { proxy } = getCurrentInstance();
const loading = ref(false);
const fileUrl = ref('');
const showPreview = ref(false);
const fileContent = ref('');
const docContent = ref('');
const excelData = ref([]);
const excelColumns = ref([]);

// 上传文件服务器地址
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload");
const headers = ref({ Authorization: "Bearer " + getToken() });

// 根据文件URL获取文件类型
const fileType = computed(() => {
  if (!fileUrl.value) return '';
  const ext = fileUrl.value.split('.').pop().toLowerCase();
  switch (ext) {
    case 'pdf':
      return 'pdf';
    case 'doc':
    case 'docx':
      return 'doc';
    case 'xls':
    case 'xlsx':
      return 'xls';
    case 'ppt':
    case 'pptx':
      return 'ppt';
    case 'txt':
      return 'txt';
    case 'jpg':
    case 'jpeg':
    case 'png':
    case 'gif':
      return 'image';
    default:
      return '';
  }
});

// 计算PDF URL
const pdfUrl = computed(() => {
  if (fileType.value === 'pdf') {
    // 如果是本地文件，使用 blob URL
    if (fileUrl.value.startsWith('blob:')) {
      return fileUrl.value;
    }
    // 如果是远程文件，使用 PDF.js viewer
    return `/pdf/web/viewer.html?file=${encodeURIComponent(fileUrl.value)}`;
  }
  return '';
});

// 预览文件
async function handlePreview() {
  if (!fileUrl.value) {
    ElMessage.warning('请输入文件路径');
    return;
  }
  loading.value = true;

  try {
    if (fileType.value === 'txt') {
      const response = await fetch(fileUrl.value);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      fileContent.value = await response.text();
    } else if (['doc', 'docx'].includes(fileType.value)) {
      const response = await fetch(fileUrl.value);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const arrayBuffer = await response.arrayBuffer();
      const result = await mammoth.convertToHtml({ arrayBuffer });
      docContent.value = result.value;
    } else if (['xls', 'xlsx'].includes(fileType.value)) {
      const response = await fetch(fileUrl.value);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const arrayBuffer = await response.arrayBuffer();
      const workbook = XLSX.read(arrayBuffer, { type: 'array' });
      const firstSheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[firstSheetName];
      const data = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
      
      if (data.length > 0) {
        // 使用第一行作为列标题
        excelColumns.value = data[0].map(col => col?.toString() || '');
        // 剩余行作为数据
        excelData.value = data.slice(1).map(row => {
          const rowData = {};
          row.forEach((cell, index) => {
            rowData[excelColumns.value[index]] = cell;
          });
          return rowData;
        });
      }
    }
    showPreview.value = true;
  } catch (error) {
    console.error('文件加载失败:', error);
    ElMessage.error('文件加载失败: ' + error.message);
    showPreview.value = false;
  }

  loading.value = false;
}

// 上传前校验
function handleBeforeUpload(file) {
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    ElMessage.error('上传文件大小不能超过 10MB!');
    return false;
  }
  loading.value = true;
  return true;
}

// 上传成功回调
async function handleUploadSuccess(response) {
  console.log('Upload response:', response);
  if (response.code === 200) {
    if (response.url) {
      fileUrl.value = response.url;
    } else if (response.fileName) {
      fileUrl.value = import.meta.env.VITE_APP_BASE_API + response.fileName;
    } else {
      ElMessage.error('上传成功但未获取到文件地址');
      return;
    }
    console.log('Final URL:', fileUrl.value);
    loading.value = true;

    try {
      if (fileType.value === 'txt') {
        const response = await fetch(fileUrl.value);
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        fileContent.value = await response.text();
      } else if (['doc', 'docx'].includes(fileType.value)) {
        const response = await fetch(fileUrl.value);
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        const arrayBuffer = await response.arrayBuffer();
        const result = await mammoth.convertToHtml({ arrayBuffer });
        docContent.value = result.value;
      } else if (['xls', 'xlsx'].includes(fileType.value)) {
        const response = await fetch(fileUrl.value);
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        const arrayBuffer = await response.arrayBuffer();
        const workbook = XLSX.read(arrayBuffer, { type: 'array' });
        const firstSheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[firstSheetName];
        const data = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
        
        if (data.length > 0) {
          // 使用第一行作为列标题
          excelColumns.value = data[0].map(col => col?.toString() || '');
          // 剩余行作为数据
          excelData.value = data.slice(1).map(row => {
            const rowData = {};
            row.forEach((cell, index) => {
              rowData[excelColumns.value[index]] = cell;
            });
            return rowData;
          });
        }
      }
      showPreview.value = true;
      ElMessage.success('文件上传成功');
    } catch (error) {
      console.error('文件加载失败:', error);
      ElMessage.error('文件加载失败: ' + error.message);
      showPreview.value = false;
    }
  } else {
    ElMessage.error(response.msg || '上传失败');
  }
  loading.value = false;
}

// 上传失败回调
function handleUploadError(error) {
  console.error('Upload error:', error);
  loading.value = false;
  ElMessage.error(error?.msg || '文件上传失败');
}
</script>

<style scoped>
.preview-header {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.preview-content {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  min-height: calc(100vh - 200px);
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.preview-content iframe,
.preview-content .el-image {
  flex: 1;
  min-height: 600px;
}

.text-preview {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
  height: 600px;
  overflow: auto;
}

.text-preview pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: Consolas, Monaco, 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.5;
}

.empty-content {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 600px;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
}

.excel-preview {
  height: 600px;
  overflow: hidden;
  background: #fff;
  border-radius: 4px;
}

.doc-preview {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  height: 600px;
  overflow: auto;
}

.pdf-preview {
  height: 600px;
  overflow: hidden;
  border-radius: 4px;
}
</style> 